package com.bigdata

import java.io.{BufferedReader, BufferedWriter, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo3IO {

  def main(args: Array[String]): Unit = {
    /**
     * 读取文件
     * 1、可以使用java中的方法
     * 2、在scala中有Source
     */
    // 输入流
    val br: BufferedReader = new BufferedReader(new FileReader("data/students.txt"))

    // 输出流
    val bw: BufferedWriter = new BufferedWriter(new FileWriter("data/students_copy.txt", true))

    var line: String = br.readLine()

    while (line != null) {
      println(line)

      bw.write(line)
      bw.newLine()
      // 读取下一行记录
      line = br.readLine()
    }

    // 刷新缓存
    bw.flush()

    // 关闭资源
    bw.close()
    br.close()

    println("=" * 100)

    // 在scala中有Source
    val source: BufferedSource = Source.fromFile("data/students.txt")

    // 从BufferedSource中读取数据
    val iter: Iterator[String] = source.getLines()

    // 把Iterator 转换为List集合
    val list: List[String] = iter.toList

    for (str <- list) {
      println(str)
    }


  }

}
